package com.mdp.tpa.wechat.wxpub.service;

import com.alibaba.fastjson.JSONObject;
import com.mdp.core.entity.LangTips;
import com.mdp.core.entity.Result;
import com.mdp.core.err.BizException;
import com.mdp.core.utils.BaseUtils;
import com.mdp.core.utils.ObjectTools;
import com.mdp.meta.client.entity.ItemVo;
import com.mdp.meta.client.entity.Option;
import com.mdp.meta.client.service.ItemService;
import com.mdp.tpa.pub.client.SysClientService;
import com.mdp.tpa.pub.entity.SysUserTpa;
import com.mdp.tpa.wechat.api.MessageSendService;
import com.mdp.tpa.wechat.wxpub.entity.NotifyMsg;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static com.mdp.core.utils.BaseUtils.map;
@Service
public class WxMsgTemplateService {

    @Autowired
    ItemService itemService;
    @Autowired
    SysClientService sysClientService;

    Set<String> idCahce=new HashSet<>();



    @Autowired
    MessageSendService messageSendService;

    public static String ITEM_CODE="wechat-wxpub-tpl";

    public String getTemplateId(String tplType){
        ItemVo itemVo=itemService.getDict("all",ITEM_CODE);
        if(itemVo==null){
            throw new BizException(LangTips.errMsg(ITEM_CODE+"-not-config","微信模板字典【%s】未配置",ITEM_CODE));
        }
        Optional<Option> option=itemVo.getOptions().stream().filter(k->tplType.equals(k.getRelyId())).findAny();
        if(!option.isPresent()){
            throw new BizException(LangTips.errMsg(ITEM_CODE+"-"+tplType+"-not-config","微信模板字典【%s】未配置选项relyId=【%s】",ITEM_CODE,tplType));
        }
        return option.get().getId();
    }


    public void sendTplMsg(Map<String,Object> message){
        String bizType = (String) message.get("bizType");
        String tplType = (String) message.get("tplType");
         String openid = (String) message.get("openid");
        String toUserid = (String) message.get("toUserid");
        String fromType=(String)message.get("fromType");
        String id= (String) message.get("id");
        String url = (String) message.get("url");
        if (!StringUtils.hasText(toUserid) && ObjectTools.isNotEmpty(openid)) {
             throw new BizException(LangTips.errMsg("toUserid-or-openid-required","发送对象不能为空"));
        }
        if(ObjectTools.isNotEmpty(id)){
            if(idCahce.contains(id)){
                return;
            }
            idCahce.add(id);
        }
        if(ObjectTools.isEmpty(tplType) && StringUtils.hasText(bizType)){
            if (bizType.equals("wfTask")) {
                tplType = "taskNotify";
            } else if (bizType.equals("pay")) {
                tplType = "payNotify";
            } else if (bizType.equals("amountChange")) {
                tplType = "amountChange";
            }
        }

        if (!StringUtils.hasText(tplType)) {
            return;
        }

        if (!"taskNotify".equals(tplType)) {
            return;
        }
        String templateId=getTemplateId(tplType);
        if(ObjectTools.isEmpty(templateId)){
            return;
        }

        List<SysUserTpa> userTpas = sysClientService.getSysUserTpaByUserid(toUserid,"wxpub",null);
        if (userTpas == null || userTpas.size()==0) {
            return;
        }
        SysUserTpa userTpa=null;
        Optional<SysUserTpa> optional=userTpas.stream().filter(k->"wxpub".equals(k.getAppType())).findFirst();
        if(optional.isPresent()){
            userTpa=optional.get();
        }else{
           optional=userTpas.stream().filter(k->"wxopen".equals(k.getAppType())).findFirst();
            if(optional.isPresent()){
                userTpa=optional.get();
            }
        }
       if(userTpa==null){
           userTpa=userTpas.get(0);
       }
        Map<String, Object> tplData = new HashMap<>();


        /**
         * {{first.DATA}} 任务名称：{{keyword1.DATA}} 相关人员：{{keyword2.DATA}} {{remark.DATA}}
         */
        String toUsername = userTpa.getUsername();
        if(!StringUtils.hasText(toUsername)){
            toUsername=userTpa.getNickname();

        }

        Map<String,Object>  result = null;
        if(message.containsKey("data")){
            tplData= (Map<String, Object>) message.get("data");
            result=messageSendService.sendTemplateMessage( templateId,userTpa.getOpenid(),url, tplData);
        }else if("notifyMsg".equals(fromType)){
            NotifyMsg msg= BaseUtils.fromMap(message,NotifyMsg.class);
            if(ObjectTools.isNotEmpty(msg.getToUsername())){
                toUsername=msg.getToUsername();
            }
            tplData.put("first", map("value", (StringUtils.hasText(toUsername)?toUsername + ",":"")+"您好," +  msg.getMsg()));
            tplData.put("keyword1", map("value", msg.getMsg()));
            tplData.put("keyword2", map("value", StringUtils.hasText(toUsername)?toUsername:""));
            tplData.put("remark", map("value", msg.getMsg()));
            result= messageSendService.sendTemplateMessage( templateId,userTpa.getOpenid(),url, tplData);
        }else if (tplType.equals("taskNotify")) {
            Map<String, Object> imParams = parseTaskNotifyMessage(message);
            tplData.put("first", map("value", (StringUtils.hasText(toUsername)?toUsername + ",":"")+"您好," + imParams.get("mainTitle")));
            tplData.put("keyword1", map("value", imParams.get("taskName")));
            tplData.put("keyword2", map("value", StringUtils.hasText(toUsername)?toUsername:""));
            tplData.put("remark", map("value", imParams.get("commentMsg")));
            result= messageSendService.sendTemplateMessage( templateId,userTpa.getOpenid(),url, tplData);
        }
        if(result!=null && !("0".equals(result.get("errcode")+""))){
             throw new BizException(LangTips.errMsg(result.get("errcode")+"",(String) result.get("errmsg")));

        }else if(result==null){
             throw new BizException(LangTips.errMsg("wx-server-no-data-back","微信服务器未返回任何数据"));

        }
    }

    /**
     *    从im过来的任务消息文本部分大部分都是下面这种格式
     * 	新任务待您处理,流程:【mainTitle】,任务:【taskName】,意见建议:commentMsg,链接:bizUrl
     *
     *   需要解析成模板中的格式
     * @param  message
     */
    public static Map<String,Object> parseTaskNotifyMessage(Map<String,Object> message){
        Map<String, Object> map=map();
        String sendContent= (String) message.get("sendContent");
        if(StringUtils.hasText(sendContent)){
            if(sendContent.indexOf(",流程:")>0){
                Matcher matcher=Pattern.compile("(.*?流程:【)(.*?)(】,)").matcher(sendContent);
                if(matcher.find()){
                    String mainTitle=matcher.group(2);
                    map.put("mainTitle",mainTitle);
                }else{
                    map.put("mainTitle","");
                }
                Matcher matcher2= Pattern.compile("(.*?任务:【)(.*?)(】,)").matcher(sendContent);
                if(matcher.find()){
                    String taskName=matcher2.group(2);
                    map.put("taskName",taskName);
                }else {
                    map.put("taskName","");
                }
                Matcher matcher3=Pattern.compile("(.*?意见建议:)(.*?)(,链接)").matcher(sendContent);
                if(matcher.find()){
                    String commentMsg=matcher3.group(2);
                    map.put("commentMsg",commentMsg);
                }else {
                    map.put("commentMsg",sendContent);
                }
            }else{
                map.put("mainTitle","");
                map.put("taskName","");
                map.put("commentMsg",sendContent);
            }
        }
        return map;
    }

    @Scheduled(cron = "0 0 0/1 * * ?")
    public void clearCache(){
        this.idCahce.clear();
    }
}
